<?php


namespace app\api\controller;


use app\admin\model\{ Records, Sales, SalesDetail, SystemUploadfile };
use app\ApiBaseController;
use think\facade\Db;

class Sale extends ApiBaseController
{
    /**
     * 添加销售记录
     */
    public function addSale()
    {
        $post = $this->request->only(['name','type','img_id','demand','qq','weixin','phone'],'post');
        $post['project_status'] = 0;
        $post['uid'] = $this->uid;
        $rule = [
            'name|客户姓名'   =>  'require|chsAlphaNum',
            'type|类型'       =>  'require|in:0,1',
            'img_id|图片'     =>  'require',
        ];
        $this->apiValidate($post, $rule);
        if (empty($post['qq']) && empty($post['weixin']) && empty($post['phone'])){
            return result(1,'联系方式至少填一个');
        }
        if (!empty($post['qq'])){
            $count = Sales::where(['uid'=>$this->uid, 'qq'=>$post['qq'], 'status'=>0])->count();
            if ($count){
                return result(1,'正在对接中的记录，QQ必须唯一');
            }
        }
        if (!empty($post['weixin'])){
            $count = Sales::where(['uid'=>$this->uid, 'weixin'=>$post['weixin'], 'status'=>0])->count();
            if ($count){
                return result(1,'正在对接中的记录，微信必须唯一');
            }
        }
        if (!empty($post['phone'])){
            $count = Sales::where(['uid'=>$this->uid, 'phone'=>$post['phone'], 'status'=>0])->count();
            if ($count){
                return result(1,'正在对接中的记录，手机号必须唯一');
            }
        }
        $img = SystemUploadfile::find($post['img_id']);
        if (empty($img)){
            return result(1,'图片id不存在');
        }
        Db::startTrans();
        try {
            $res = Sales::create($post);
            SalesDetail::create(['sales_id' => $res->id, 'uploadfile_id' => $post['img_id']]);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return result(1,'添加失败：'.$e->getMessage());
        }
        return result(0,'添加成功');
    }

    /**
     * 将某个销售记录状态设置成已失败
     */
    public function setSaleFail()
    {
        $id = $this->request->param('id/d');
        $data = Sales::find($id);
        if (empty($data)){
            return result(1,'记录不存在');
        }
        if ($data->uid <> $this->uid){
            return result(1,'只能操作自己的记录');
        }
        if ($data->status){
            return result(1,'请勿重复设置');
        }
        try {
            $data->status = 1;
            $data->save();
        }catch (\Exception $e){
            return result(1,'设置失败：'.$e->getMessage());
        }
        return result(0,'设置成功');
    }

    /**
     * 按类型批量获取销售记录  0对接中 1已失败
     */
    public function getSalesList()
    {
        $status = $this->request->param('status/d', 0);
        if (!in_array($status, [0,1])){
            return result(1,'类型不存在');
        }
        $data = Sales::where(['uid' => $this->uid, 'status' => $status])
            ->order('update_time','asc')
            ->hidden(['delete_time','update_time'])
            ->select();
        if ($data->isEmpty()){
            return result(0, '', []);
        }
        foreach ($data as $k => $v){
            $data[$k]['true_name'] = $this->user->true_name;
        }
        return result(0, '', $data);
    }

    /**
     * 获取单条销售记录
     */
    public function getSale()
    {
        $id = $this->request->param('id/d');
        $data = Sales::find($id);
        if (empty($data)){
            return result(1,'记录不存在');
        }
        if ($data->uid <> $this->uid){
            return result(1,'只能获取自己的记录');
        }
        $data = $data->hidden(['delete_time','update_time']);
        $data['true_name'] = $this->user->true_name;
        return result(0, '', $data);
    }

    /**
     * 获取某条销售记录的所有追销记录
     */
    public function getSaleAllDetails()
    {
        $id = $this->request->param('id/d');
        $data = Sales::find($id);
        if (empty($data)){
            return result(1,'记录不存在');
        }
        if ($data->uid <> $this->uid){
            return result(1,'只能获取自己的记录');
        }
        $data = $data->images->visible(['url', 'create_time']);
        if ($data->isEmpty()){
            return result(0, '', []);
        }
        $data['res'] = $data->toArray();
        $data['today'] = 0;
        $count = SalesDetail::whereDay('create_time')->where('sales_id', $id)->count();
        if ($count){
            $data['today'] = 1;
        }
        return result(0, '', $data);
    }

    /**
     * 追销
     */
    public function addSaleDetail()
    {
        $post = $this->request->param();
        $rule = [
            'id|销售记录ID'     =>  'require|number',
            'img_id|上传图片ID' =>  'require|number',
        ];
        $this->apiValidate($post, $rule);
        $data = Sales::find($post['id']);
        if (empty($data)){
            return result(1,'记录不存在');
        }
        if ($data->uid <> $this->uid){
            return result(1,'只能操作自己的记录');
        }
        if ($data->status){
            return result(1,'记录被标记为失败，无法追销');
        }
        $img = SystemUploadfile::find($post['img_id']);
        if (empty($img)){
            return result(1,'图片id不存在');
        }
        $is_today = SalesDetail::where('sales_id', $post['id'])
            ->whereDay('create_time')
            ->count();
        if ($is_today){
            $img->delete();
            return result(1,'单个记录每天只能追销一次');
        }
        $count = SalesDetail::where('sales_id', $post['id'])->count();
        if ($count < 3){
            $project_status = $count;
        }else{
            $project_status = 2;
        }
        Db::startTrans();
        try {
            SalesDetail::create(['sales_id'=>$post['id'],'uploadfile_id'=>$post['img_id']]);
            Sales::update(['project_status'=>$project_status],['id'=>$post['id']]);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return result(1, '追销失败:'.$e->getMessage());
        }
        return result(0,'追销成功');
    }

    /**
     * 销售记录出单
     */
    public function submitSale()
    {
        $post = $this->request->post();
        $rule = [
            'id|销售记录ID'         =>  'require|number',
            'total_amount|成交金额' =>  'require|float',
            'pay_amount|已手金额'   =>  'require|float',
            'ratio|提成比例'        =>  'require|float',
        ];
        $this->apiValidate($post, $rule);
        $data = Sales::find($post['id']);
        if (empty($data)){
            return result(1,'记录不存在');
        }
        if ($data->status){
            return result(1,'记录已失败，无法出单');
        }
        Db::startTrans();
        try{
            Records::create([
                'audit_type'    =>  1,
                'uid'           =>  $this->uid,
                'name'          =>  $data->name ?? '',
                'type'          =>  $data->type,
                'demand'        =>  $data->demand ?? '',
                'phone'         =>  $data->phone ?? '',
                'qq'            =>  $data->qq ?? '',
                'weixin'        =>  $data->weixin ?? '',
                'total_amount'  =>  $post['total_amount'],
                'pay_amount'    =>  $post['pay_amount'],
                'ratio'         =>  $post['ratio'],
            ]);
            $data->project_status = 3;
            $data->save();
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return result(1, '出单失败'.$e->getMessage());
        }
        return result(0,'出单成功');
    }
}